﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Gman.Entity.Entities;
using Gman.WebApp.ServiceControllers;
using Gman.WebApp.Models;
using System.Web.Caching;
using System.Web.UI;
using Gman.WebApp.Controllers.Base;

namespace Gman.WebApp.Controllers
{
    public class SedeController : BaseController
    {
        private IList<SedeBE> lista = new List<SedeBE>();
        protected static List<PersonalBE> personalDelete = new List<PersonalBE>();
   

        public ActionResult Search()
        {
            var cache = new CacheProvider();
            SedeBE sede = new SedeBE();
            UbigeoBE ubigeo = new UbigeoBE();

            var model = new SedeModel(sede, ubigeo);
            cache.Set(model.ID.Value.ToString(), model);

            model.Action = "search";
            model.ToolBar = new ToolBarModel();

            return View(@"~/Views/Sede/Edit.aspx", model);
        }

        public ActionResult DoSearch(string codigo)
        {
            var cache = new CacheProvider();

            UsuariosBE user = (UsuariosBE)Session["user"];
            UbigeoBE ubigeo = new UbigeoBE();

            SedeBE obj = new SedeBE();
            obj.CodSede = codigo;
            obj.IDEmp = user.IDEmp;
            

            var sede = OperacionServiceController.ObtenerSede(obj);
            if (sede != null)
            {
                var model = new SedeModel(sede,ubigeo);
                cache.Set(model.ID.Value.ToString(), model); 
                model.Action = "query";
                model.ToolBar = new ToolBarModel();
                ubigeo.CodDpto = sede.CodUbigeo.Substring(0, 2);
                ubigeo.CodProv = sede.CodUbigeo.Substring(2, 2);
                ubigeo.CodDist = sede.CodUbigeo.Substring(4, 2);

                model.Departamento = new SelectList(GeneralServiceController.ListarUbigeo(new UbigeoBE(), 1), "CodDpto", "DescUbigeo", model.Departamento);
                model.Provincia = new SelectList(GeneralServiceController.ListarUbigeo(ubigeo, 2), "CodProv", "DescUbigeo", model.Provincia);
                model.Distrito = new SelectList(GeneralServiceController.ListarUbigeo(ubigeo, 3), "CodDist", "DescUbigeo", model.Distrito);

                Int64 IDSede = Convert.ToInt64(model.Sede.IDSede);
                TempData["IDSede"] = IDSede;

                model.Personales = new List<PersonalModel>();

                IList<PersonalBE> listaPersonal = new List<PersonalBE>();
                PersonalBE p = new PersonalBE();
                p.IDOrigen = IDSede;
                p.OrigenPers = 1;
                p.IDEmp = user.IDEmp;
                listaPersonal = OperacionServiceController.ListarPersonal(p);

                foreach (PersonalBE persSede in listaPersonal) {
                    model.Personales.Add(new PersonalModel(persSede));
                }

                return View(@"~/Views/Sede/Edit.aspx", model);
            }

            return AjaxResultSuccess(string.Format("No se encontró sede :{0} ", codigo));
        }

        public ActionResult Create()
        {
            var cache = new CacheProvider();
            SedeBE sede = new SedeBE();
            UbigeoBE ubigeo = new UbigeoBE();

            var model = new SedeModel(sede, ubigeo);
            cache.Set(model.ID.Value.ToString(), model);
            model.Action = "create";
            model.ToolBar = new ToolBarModel();

            return View(@"~/Views/Sede/Edit.aspx", model);
        }

        public ActionResult Edit(string CodSede)
        {
            var cache = new CacheProvider();

            UsuariosBE user = (UsuariosBE)Session["user"];
            UbigeoBE ubigeo = new UbigeoBE();

            SedeBE obj = new SedeBE();
            obj.CodSede = CodSede;
            obj.IDEmp = user.IDEmp;


            var sede = OperacionServiceController.ObtenerSede(obj);
            if (sede != null)
            {
                var model = new SedeModel(sede, ubigeo);
                cache.Set(model.ID.Value.ToString(), model);
                model.Action = "edit";
                model.ToolBar = new ToolBarModel();
                ubigeo.CodDpto = sede.CodUbigeo.Substring(0, 2);
                ubigeo.CodProv = sede.CodUbigeo.Substring(2, 2);
                ubigeo.CodDist = sede.CodUbigeo.Substring(4, 2);

                model.Departamento = new SelectList(GeneralServiceController.ListarUbigeo(new UbigeoBE(), 1), "CodDpto", "DescUbigeo", model.Departamento);
                model.Provincia = new SelectList(GeneralServiceController.ListarUbigeo(ubigeo, 2), "CodProv", "DescUbigeo", model.Provincia);
                model.Distrito = new SelectList(GeneralServiceController.ListarUbigeo(ubigeo, 3), "CodDist", "DescUbigeo", model.Distrito);

                model.Personales = new List<PersonalModel>();

                IList<PersonalBE> listaPersonal = new List<PersonalBE>();
                PersonalBE p = new PersonalBE();
                p.IDOrigen = model.Sede.IDSede;
                p.OrigenPers = 1;
                p.IDEmp = user.IDEmp;
                listaPersonal = OperacionServiceController.ListarPersonal(p);

                foreach (PersonalBE persSede in listaPersonal)
                {
                    model.Personales.Add(new PersonalModel(persSede));
                }


                return View(@"~/Views/Sede/Edit.aspx", model);
            }

            return RedirectToAction("Search");
        }

        public JsonResult Save(Guid id, string action)
        {
            try
            {
                UsuariosBE user = (UsuariosBE)Session["user"];
                SedeModel model = GetSedeModel(id);

                if (model.Action == "create")
                {
                    SedeBE obj = new SedeBE();
                    obj.CodSede = "SD-" + (ListaSede().Count + 1);
                    obj.NomSede = model.Sede.NomSede;
                    obj.CodUbigeo = model.Ubigeo.CodDpto + model.Ubigeo.CodProv + model.Ubigeo.CodDist;

                    obj.DirecSede = model.Sede.DirecSede;
                    obj.TlfSede = model.Sede.TlfSede;
                    obj.UsuReg = user.NomUsu;
                    obj.TermCnxReg = Environment.MachineName;
                    obj.EstadoSede = 1;
                    obj.IDEmp = user.IDEmp;

                    int IDSede = OperacionServiceController.RegistrarSede(obj);

                    int pesonalSede = model.Personales.Count;

                    if (pesonalSede > 0)
                    {
                        //List<PersonalBE> x = new List<PersonalBE>();
                        foreach (var per in model.Personales)
                        {
                            per.Personal.OrigenPers = 1;
                            per.Personal.IDOrigen = IDSede;
                            per.Personal.UsuReg = user.NomUsu; ;
                            per.Personal.TermCnxReg = Environment.MachineName;
                            OperacionServiceController.RegistrarPersonal(per.Personal);
                        }
                    }


                    if (IDSede >= 1)
                    {
                        TempData["IDSede"] = IDSede;
                        return AjaxResultSuccess(string.Format("Sede {0} se guardo exitosamente.", obj.CodSede));
                    }
                    else
                    {
                        return AjaxResultSuccess(string.Format("No se guardo exitosamente."));
                    }
                }

                if (model.Action == "edit")
                {
                    model.Sede.UsuMod = user.NomUsu;
                    model.Sede.TermCnxMod = Environment.MachineName;
                    model.Sede.CodUbigeo = model.Ubigeo.CodDpto + model.Ubigeo.CodProv + model.Ubigeo.CodDist;
                    int resultado = OperacionServiceController.ActualizarSede(model.Sede);

                    int pesonalSede = model.Personales.Count ;

                    if (pesonalSede > 0) {
                        //List<PersonalBE> x = new List<PersonalBE>();
                        foreach (var per in model.Personales) {
                            if(per.Personal.IDPersonal > 0){
                                per.Personal.UsuMod = user.NomUsu; ;
                                per.Personal.TermCnxMod = Environment.MachineName;
                                OperacionServiceController.ActualizarPersonal(per.Personal);
                            }

                            else
                            {
                                per.Personal.IDOrigen = model.Sede.IDSede;
                                per.Personal.UsuReg = user.NomUsu; ;
                                per.Personal.OrigenPers = 1; // INDICAMOS Q ES PERSONAL DE SEDE
                                per.Personal.TermCnxReg = Environment.MachineName;
                                per.Personal.IDEmp = user.IDEmp;
                                OperacionServiceController.RegistrarPersonal(per.Personal);
                            }
                        }
                    }


                    /*VERIFICANDO SI EXISTEN PERSONAL ELIMINADO*/

                    int eliminados = personalDelete.Count;

                    if (eliminados > 0)
                    {
                        foreach (PersonalBE per in personalDelete)
                        {
                            per.UsuMod = user.NomUsu; ;
                            per.TermCnxMod = Environment.MachineName;
                            OperacionServiceController.EliminarPersonal(per);
                        }
                        personalDelete.Clear();
                    }

                    

                    if (resultado == 1)
                    {
                        return AjaxResultSuccess(string.Format("Sede {0} se guardo exitosamente.", model.Sede.IDSede));
                    }

                    else
                    {
                        return AjaxResultSuccess(string.Format("No se guardo exitosamente."));
                    }
                }

                return AjaxResultSuccessNoParam();
            }
            catch (Exception ex)
            {
                return AjaxResultError(ex.Message);
            }
        }

        public JsonResult SeleccionarDepartamentoProvincia(string Sel_Dpto)
        {
            UbigeoBE ubi = new UbigeoBE();
            ubi.CodDpto = Sel_Dpto;

            JsonResult result = new JsonResult();
            var vPrvncias = GeneralServiceController.ListarUbigeo(ubi, 2);
            result.Data = vPrvncias.ToList();
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;

        }

        public JsonResult SeleccionarDistritoProvincia(string Sel_Prov, string Sel_Dpto)
        {
            UbigeoBE ubi = new UbigeoBE();
            ubi.CodProv = Sel_Prov;
            ubi.CodDpto = Sel_Dpto;

            JsonResult result = new JsonResult();
            var vDistritos = GeneralServiceController.ListarUbigeo(ubi, 3);
            result.Data = vDistritos.ToList();
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }

        private IList<SedeBE> ListaSede() {
            
            UsuariosBE user = (UsuariosBE)Session["user"];
            SedeBE sede = new SedeBE();
            sede.IDEmp =user.IDEmp;
            lista = OperacionServiceController.ListarSede(sede);
            return lista;
        }

        private SedeBE ObtenerSede(SedeBE s) {
            SedeBE sede = new SedeBE();
            sede = OperacionServiceController.ObtenerSede(s);
            return sede;
        }    

        public JsonResult AddOrEditPersonal(Guid id, Guid personalGuid, string action)
        {
            try
            {
                var personal = new PersonalController().GetPersonalModel(personalGuid);
                var model = GetSedeModel(id);
                if (action == "create")
                {
                    personal.Personal.IDPersonal = 0;
                    model.Personales.Add(personal);
                }
                else if (action == "edit")
                {
                    var personalToEdit = model.Personales.FirstOrDefault(x => x.ID == personalGuid);
                    personalToEdit = personal;
                }

                return AjaxResultSuccessNoParam();
            }
            catch (Exception ex)
            {
                return AjaxResultError(ex.Message);
            }
        }

        public ViewResult DeletePersonal(Guid id, Guid personalGuid)
        {
            var model = GetSedeModel(id);
            var personal = model.Personales.FirstOrDefault(x => x.ID == personalGuid);
            personalDelete.Add(personal.Personal);
            model.Personales.Remove(personal);

            return View(@"~/Views/Sede/ListaPersonal.ascx", model);   
        }

        public ViewResult LoadAddOrEditPersonal(Guid id, Guid? personalGuid)
        {
            var cache = new CacheProvider();
            PersonalModel personal = null;
            if (!personalGuid.HasValue)
            {
                personal = new PersonalModel(new PersonalBE());
                personal.Action = "create";
                cache.Set(personal.ID.Value.ToString(), personal);
            }
            else
            {
                var sedeModel = GetSedeModel(id);
                personal = sedeModel.Personales.FirstOrDefault(x => x.ID == personalGuid.Value);                
                personal.Action = "edit";
                if (personal.Personal.IDPersonal.HasValue)
                {
                    cache.Set(personalGuid.Value.ToString(), personal);    
                }
            }
            return View(@"~/Views/Personal/AddOrEdit.ascx", personal);
        }

        public SedeModel GetSedeModel(Guid id)
        {
            var cache = new CacheProvider();

            string key = id.ToString();
            var existingModel = cache.Get(key);
            if (existingModel == null)
            {
                existingModel = new SedeModel(new SedeBE());
                cache.Set(key, existingModel);
            }
            return (SedeModel)existingModel;
        }

        public ActionResult UpdateField(string fieldName, string fieldValue, Guid id, string setterFormatOptions)
        {
            SedeModel model = GetSedeModel(id);
            SetterFormatOptions setterFormatOptionsEnum = SetterFormatOptionsHelper.Parse(setterFormatOptions);
            List<KeyValuePair<string, string>> validationList = new List<KeyValuePair<string, string>>();            

            var setter = new PropertySetter<SedeModel>.SetterOptions();
            setter.objectToSet = model;
            setter.property = fieldName;
            setter.val = fieldValue;
            setter.SetterFormatOptions = setterFormatOptionsEnum;
            setter.validationList = validationList;

            object valueWasSet = PropertySetter<SedeModel>.SetFinalObject(setter);           

            validationList.AddRange(new SedeModelValidator().Validate(model));

            return Json
                (new
                {
                    result = true,
                    PropertyValidationList = validationList                   
                }
                );
        }

        public ActionResult GetValidation(Guid id)
        {
            SedeModel model = GetSedeModel(id);
            List<KeyValuePair<string, string>> validationList = new List<KeyValuePair<string, string>>();
            List<KeyValuePair<string, string>> propertyChangeList = new List<KeyValuePair<string, string>>();

            validationList.AddRange(new SedeModelValidator().Validate(model));

            return Json(new
            {
                PropertyValidationList = validationList,
                PropertyVisibilityList = propertyChangeList
            });
        }

        public ViewResult GetListaPersonal(Guid id)
        {
            SedeModel model = GetSedeModel(id);
            PersonalBE p = new PersonalBE();
                                   
            return View(@"~/Views/Sede/ListaPersonal.ascx", model);
        }
    }
}
